import { RollupWebRuntime } from "../RollupWebRuntime";
import Worker from "./worker?worker";
import { expose } from "comlink";
export class WorkerRuntime extends RollupWebRuntime {
    init(config: {}): void {
        Object.assign(this, config);
    }
    compiler: Worker;
    async build() {
        const port = await this.Compiler.createPort(); // 构建 Compiler 线程, 已经经过去重
        const compiler = new Worker();
        const channel = new MessageChannel();
        this.test.init(channel.port1);

        this.compiler = compiler;

        compiler.addEventListener(
            "message",
            (e) => {
                if (e.data === "__rollup_ready__") {
                    compiler.postMessage(
                        {
                            password: "__rollup_init__",
                            localURL: new URL(
                                "/src/index.js",
                                location.href
                            ).toString(),
                            port,
                            testPort: channel.port2,
                            testUrl: new URL(
                                "/test/index.test.js",
                                location.href
                            ).toString(),
                        },
                        [port, channel.port2]
                    );
                    return true;
                }
            },
            { once: true }
        );
    }
    async reload() {
        this.compiler?.terminate();
        this.build();
    }
    async destroy() {
        this.compiler?.terminate();
        super.destroy();
    }
}
